package com.fh.huanxin.controller;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fh.huanxin.HTTPClientUtils;
import com.fh.huanxin.com.Constants;
import com.fh.huanxin.com.Roles;
import com.fh.huanxin.vo.ClientSecretCredential;
import com.fh.huanxin.vo.Credential;
import com.fh.huanxin.vo.EndPoints;
import com.fh.util.Logger;

public class HxFiles {
	protected static Logger logger = Logger.getLogger(HxFiles.class);
	private static final String APPKEY = Constants.APPKEY;
	private static final JsonNodeFactory factory = new JsonNodeFactory(false);

	// 通过app的client_id和client_secret来获取app管理员token
	private static Credential credential = new ClientSecretCredential(Constants.APP_CLIENT_ID,
			Constants.APP_CLIENT_SECRET, Roles.USER_ROLE_APPADMIN);

	private void mian() {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * TODO 方法作用：上传图片文件
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:39:50
	 */
	public static Object uploadImgFile() {
		File uploadImgFile = new File("/home/lynch/Pictures/24849.jpg");
		ObjectNode imgDataNode = mediaUpload(uploadImgFile);

		if (null != imgDataNode) {
		}
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return imgDataNode;

	}

	/**
	 * 
	 * TODO 方法作用：下载图片文件
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:40:26
	 */
	public static Object downloadImgFile() {
		File uploadImgFile = new File("/home/lynch/Pictures/24849.jpg");
		ObjectNode imgDataNode = mediaUpload(uploadImgFile);
		String imgFileUUID = imgDataNode.path("entities").get(0).path("uuid").asText();
		String shareSecret = imgDataNode.path("entities").get(0).path("share-secret").asText();
		File downloadedImgFileLocalPath = new File(uploadImgFile.getPath().substring(0,
				uploadImgFile.getPath().lastIndexOf("."))
				+ "-1.jpg");
		boolean isThumbnail = false;
		ObjectNode downloadImgDataNode = mediaDownload(imgFileUUID, shareSecret, downloadedImgFileLocalPath,
				isThumbnail);
		if (null != downloadImgDataNode) {
			logger.info("下载图片文件: " + downloadImgDataNode.toString());
		}
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return downloadImgDataNode;

	}

	/**
	 * 
	 * TODO 方法作用：下载略缩图
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:43:08
	 */
	public static Object downloadImgFileShrinkage() {
		File uploadImgFile = new File("/home/lynch/Pictures/24849.jpg");
		ObjectNode imgDataNode = mediaUpload(uploadImgFile);
		String imgFileUUID = imgDataNode.path("entities").get(0).path("uuid").asText();
		String shareSecret = imgDataNode.path("entities").get(0).path("share-secret").asText();

		File downloadedLocalPathThumnailImg = new File(uploadImgFile.getPath().substring(0,
				uploadImgFile.getPath().lastIndexOf("."))
				+ "-2.jpg");

		boolean isThumbnail = true;
		ObjectNode downloadThumnailImgDataNode = mediaDownload(imgFileUUID, shareSecret,
				downloadedLocalPathThumnailImg, isThumbnail);
		if (null != downloadThumnailImgDataNode) {
			logger.info("下载缩略图: " + downloadThumnailImgDataNode.toString());
		}
		return downloadThumnailImgDataNode;

	}

	/**
	 * 
	 * TODO 方法作用：上传语音文件
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:49:32
	 */
	public static Object uploadAudioFile() {
		File uploadAudioFile = new File("/home/lynch/Music/music.MP3");
		ObjectNode audioDataNode = mediaUpload(uploadAudioFile);
		if (null != audioDataNode) {
			logger.info("上传语音文件: " + audioDataNode.toString());
		}

		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return audioDataNode;

	}

	/**
	 * 
	 * TODO 方法作用：下载语音文件
	 * 
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:50:58
	 */
	public static Object downloadAudioFile() {
		File uploadAudioFile = new File("/home/lynch/Music/music.MP3");
		ObjectNode audioDataNode = mediaUpload(uploadAudioFile);
		String audioFileUUID = audioDataNode.path("entities").get(0).path("uuid").asText();
		String audioFileShareSecret = audioDataNode.path("entities").get(0).path("share-secret").asText();
		File audioFileLocalPath = new File(uploadAudioFile.getPath().substring(0,
				uploadAudioFile.getPath().lastIndexOf("."))
				+ "-1.MP3");
		ObjectNode downloadAudioDataNode = mediaDownload(audioFileUUID, audioFileShareSecret, audioFileLocalPath, null);
		if (null != downloadAudioDataNode) {
			logger.info("下载语音文件: " + downloadAudioDataNode.toString());
		}
		return downloadAudioDataNode;

	}

	/**
	 * 图片/语音文件上传
	 * 
	 * @param uploadFile
	 * 
	 */
	public static ObjectNode mediaUpload(File uploadFile) {

		ObjectNode objectNode = factory.objectNode();

		if (!uploadFile.exists()) {

			logger.error("file: " + uploadFile.toString() + " is not exist!");

			objectNode.put("message", "File or directory not found");

			return objectNode;
		}

		if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			logger.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {

			List<NameValuePair> headers = new ArrayList<NameValuePair>();
			headers.add(new BasicNameValuePair("restrict-access", "true"));

			objectNode = HTTPClientUtils.uploadFile(EndPoints.CHATFILES_URL, uploadFile, credential, headers);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}

	/**
	 * 图片语音文件下载
	 * 
	 * 
	 * @param fileUUID
	 *            文件在DB的UUID
	 * @param shareSecret
	 *            文件在DB中保存的shareSecret
	 * @param localPath
	 *            下载后文件存放地址
	 * @param isThumbnail
	 *            是否下载缩略图 true:缩略图 false:非缩略图
	 * @return
	 */
	public static ObjectNode mediaDownload(String fileUUID, String shareSecret, File localPath, Boolean isThumbnail) {

		ObjectNode objectNode = factory.objectNode();

		File downLoadedFile = null;

		if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			logger.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		try {

			List<NameValuePair> headers = new ArrayList<NameValuePair>();
			if (!StringUtils.isEmpty(shareSecret)) {
				headers.add(new BasicNameValuePair("share-secret", shareSecret));
			}
			headers.add(new BasicNameValuePair("Accept", "application/octet-stream"));
			if ((isThumbnail != null) && isThumbnail) {
				headers.add(new BasicNameValuePair("thumbnail", String.valueOf(isThumbnail)));
			}

			URL mediaDownloadUrl = HTTPClientUtils
					.getURL(Constants.APPKEY.replace("#", "/") + "/chatfiles/" + fileUUID);
			downLoadedFile = HTTPClientUtils.downLoadFile(mediaDownloadUrl, credential, headers, localPath);

		} catch (Exception e) {
			e.printStackTrace();
		}

		logger.error("File download successfully，file path : " + downLoadedFile.getAbsolutePath() + ".");

		objectNode.put("message", "File download successfully .");

		return objectNode;
	}

}
